﻿using System;
using System.IO;
using System.Linq;
using Sustainalytics.DataLayer;
using Sustainalytics.DataLayer.Shared;
using MongoDB.Driver.Builders;

namespace Sustainalytics.CarbonData.BussinesLogic
{
    public interface IFileUpload
    {
        //PICompanyAssessment ReadCompanyAssessment(List<int> userUniverseIds, List<string> claimedIndicators, Guid companyId);
        //IEnumerable<PIIndicator> ReadPIIndicators();
        //IEnumerable<string> ReadOwnershipValues();
        //CorporateData GetCorporateDataByCompanyId(Guid companyId);
        //IEnumerable<PICompanyAssessment> ReadCompanyAssessment(int skip, int take, string sort, bool sortascending);
        //IEnumerable<PICompanyAssessmentShortReport> ReadCompanyAssessmentShortReport(PIAssessmentListFilters filters, List<int> userUniverseIds, List<string> claimedIndicators, int skip, int take, string[] orderBy = null, bool orderByAsc = true);
        //long ReadCompanyAssessmentShortReportCount(PIAssessmentListFilters filters, List<int> userUniverseIds, List<string> claimedIndicators);

        //input file 
        CarbonDataInputFile CreateAndValidateInputFile(Guid id, Stream file, string filename, out ValidationResult result);

        CarbonDataInputFile ReadLatestInputFileHistory();

        bool CancelInputFile(Guid id);

        //IList<PICategory> GetIndicatorCategories(string piSymbol);
        //Guid GetTemplateCriteriaIdByPISymbol(string piSymbol);
    }

    public class FileUpload : IFileUpload
    {
        IFileRepository _fileRepository;
        readonly IRepositoryCollection<CarbonDataInputFile> _inputFileRepository;
        ExcelFileImport _updater; 

        public FileUpload()
        {
        }

        public FileUpload(IFileRepository fileRepository,
            IRepositoryCollection<CarbonDataInputFile> inputFileRepository,
            ExcelFileImport updater)
        {
            _fileRepository = fileRepository;
            _inputFileRepository = inputFileRepository;
            _updater = updater;
        }

        public CarbonDataInputFile ReadLatestInputFileHistory()
        {
            var result = _inputFileRepository.Collection()
                .FindAllAs<CarbonDataInputFile>()
                .SetSortOrder(SortBy.Descending("History.DateTime"))
                .SetLimit(1)
                .FirstOrDefault();

            return result;
        }

        public CarbonDataInputFile CreateAndValidateInputFile(Guid id, Stream content, string filename, out ValidationResult result)
        {
            // create
            var newFile = new CarbonDataInputFile()
            {
                Id = id,
                Name = filename,
            };

            var inputHistory = new InputHistory
            {
                DateTime = DateTime.UtcNow,
                Status = UploadStatus.UploadInvalid
            };

            newFile.History.Add(inputHistory);


            _inputFileRepository.Create(newFile);

            // validate 
            try
            {
                result = _updater.Validate(content);

                inputHistory.Details = result.Details;

                if (result.Success)
                {
                    inputHistory.Status = UploadStatus.UploadValid;
                }

                _inputFileRepository.Update(newFile.Id, newFile);
            }
            finally
            {
                content.Close();
            }

            return newFile;
        }

        public virtual bool CancelInputFile(Guid id)
        {
            var inputFile = _inputFileRepository.Read(id);
            if (inputFile == null)
                throw new ResourceNotFound("InputFile", id);

            inputFile.History.Add(new InputHistory() { DateTime = DateTime.UtcNow, Status = UploadStatus.Canceled });

            _inputFileRepository.Update(inputFile.Id, inputFile);

            return true;
        }

    }
}
